package com.tqz.rc.common.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.tqz.rc.common.exception.RcException;

import java.io.IOException;

/**
 * <p>jackson工具类
 *
 * @author tianqingzhao
 * @since 2021/8/27 15:01
 */
public class JacksonUtils {

    static ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 对象转json
     *
     * @param obj 对象
     * @return
     */
    public static String toJson(Object obj) {
        try {
            return objectMapper.writeValueAsString(obj);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * json转对象
     *
     * @param json json字符串
     * @param cls  类型
     * @param <T>  泛型
     * @return
     */
    public static <T> T toObj(String json, Class<T> cls) {
        try {
            return objectMapper.readValue(json, cls);
        } catch (Exception e) {
            throw new RuntimeException(cls.getSimpleName() + "转json异常。", e);
        }
    }
}
